
import time
from selenium.webdriver.support.ui import WebDriverWait  #“显示等待”模块
from selenium.webdriver.common.by import By   #寻找元素模块
from selenium.webdriver.support import expected_conditions as EC  #等待条件模块

#循环监控页面两个车次是否有票，有就停止循环
def monitorUntilPresent(browser,trainNum1,trainNum2):
    isTicketPresent = False
    while isTicketPresent==False:
        try:
            print('Monitor ' + trainNum1 + '...')
            print('Now:' + time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) )  
            #//*[@id="ticket_650000Z23002"]
            WebDriverWait(browser,10,1).until(EC.presence_of_element_located((By.ID,trainNum1 )))
            #点击该行车次TR最后一个TD的“预订”按钮
            print('Found ticket at ' + trainNum1 +',Click 预订按钮！')
            browser.find_element_by_xpath('//tr[@id="' + trainNum1 +'"]/td[13]/a').click()
            isTicketPresent = True
        except:
            try:
                print('TrainNum1 Failured! Monitor ' + trainNum2 +'...')
                browser.find_element_by_id('query_ticket').click()
                WebDriverWait(browser,10,1).until(EC.presence_of_element_located((By.ID, trainNum2)))
                print('Found ticket at ' + trainNum2 +',Click 预订按钮！')
                browser.find_element_by_xpath('//tr[@id="' + trainNum2 +'"]/td[13]/a').click()
                isTicketPresent = True
            except:
                print('TrainNum2 Failured!')    
        #间隔10秒再刷新一次，可调整，但频率过高会被服务端断开连接
        time.sleep(10)           

def login(browser):
    time.sleep(8)
    isValidateSuc = False;
    while isValidateSuc==False:
        try:
            #点击登陆操作，该id为登陆按钮
            print('Click 登录按钮  01')
            browser.find_element_by_id('loginSub').click()
            isValidateSuc = True
            #或者 browser.find_element_by_link_text('登陆').click()  #标签显示的名称
        except:
            print('Captcha Error 01!')
            #try中验证码输入点错了会在此处刷新一次
            browser.find_element_by_class_name('touclick-bgimg touclick-reload touclick-reload-normal').click()
            #第二次输入验证码前等待20秒，可以自己设置，第一次输入无误直接跳过
            time.sleep(9)
            #跳转到车票预定页面time.sleep(2) #重新输入验证码后的点击登陆
            browser.find_element_by_id('loginSub').click()
            print('Click 登录按钮  02')
            
